package com.ant.storage.service.impl;

import com.ant.storage.common.ResultCode;
import com.ant.storage.dto.CnyhrjzDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.CnyhrjzMapper;
import com.ant.storage.pojo.Cnyhrjz;
import com.ant.storage.pojo.UserInfo;
import com.ant.storage.service.ICnyhrjzService;
import com.ant.storage.service.IDataMsgService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author melon
 * @since 2022-11-30
 */
@Service
//@DS("four")
public class CnyhrjzServiceImpl extends ServiceImpl<CnyhrjzMapper, Cnyhrjz> implements ICnyhrjzService {

    @Autowired
    private IDataMsgService dataMsgService;

    @Autowired
    private ICnyhrjzService cnyhrjzService;

    @Autowired
    public ServletContext servletContext;

    @Override
    public List<Cnyhrjz> getList(CnyhrjzDto dto) throws Exception {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if(userInfo == null){
            throw new AntException(ResultCode.FAILURE.getCode(),"请登录");
        }
        //切换数据库
        try{
            // dataMsgService.changeDb(userInfo.getCityId());
           // dataMsgService.changeDb(dto.getCityId());
            dataMsgService.changeDb(100);
        }catch (Exception e){
            throw new AntException(ResultCode.FAILURE.getCode(),"数据库连接失败");
        }
        QueryWrapper<Cnyhrjz> wrapper=new QueryWrapper<>();
        if(dto.getFkmId()==null || ("").equals( dto.getFkmId())){
            throw new AntException(ResultCode.FAILURE.getCode(),"请输入科目id");
        }
        if(dto.getFyear()==null || ("").equals( dto.getFyear())){
            throw new AntException(ResultCode.FAILURE.getCode(),"请选择年份");
        }
        if(dto.getKeyword()==null || ("").equals( dto.getKeyword())){
            throw new AntException(ResultCode.FAILURE.getCode(),"请选择月份");
        }
        wrapper.eq("FPeriod",dto.getKeyword());
        wrapper.eq("FKmId",dto.getFkmId());
        wrapper.eq("FYear",dto.getFyear());
        wrapper.orderByAsc("FDate");
        return  this.baseMapper.selectList(wrapper);
    }

    @Override
    public void saveMsg(Cnyhrjz cnyhrjz) throws Exception {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if(userInfo == null){
            throw new Exception("请登录");
        }
        dataMsgService.changeDb(userInfo.getCityId());
        cnyhrjzService.saveMsg(cnyhrjz);
    }
}
